var express = require('express');
var router = express.Router();
const {uploadFiles,moveFiles,removeFiles}=require('../utils/uploadFiles')

const {getOrders,updateOrders,addOrders} = require("../service/ordersService")

//获取订单
router.get('/getOrders', async function (req, res, next) {

  const data = await getOrders(req.query)
    res.send(data)
});

//修改订单
router.post('/updateOrders', async function (req, res, next) {

  const data = await updateOrders(req.body)

    res.send(data)
});



// router.post('/addOrders', async function (req, res, next) {
//   const data = await addOrders(req.body)
//     res.send(data)
// });

const images=uploadFiles({
  path:'./public/temp',//用来设置上传成功后的图片存储路径
  key:'file',//key的值与前端formData.append('file','files[0])中file名字要一致
fileSize:100
});

// 图片上传
router.post('/uploadImages',async function(req,res,next){
  // console.info(req.files)
// res.send(req.files.map(item=>item.filename))
images(req, res, function (err) {
  if (err) {
      console.log(err.code);
      if (err.code === 'LIMIT_FILE_SIZE') {
          res.send({ success: false, msg: '文件过大' });
      }
  } else {
      // console.log(req.files);
      res.send({ success: true, filename: req.files[0].filename });
      // res.send({ success: true, filename:req.files.map(item=>item.filename) });
  }

});
})

//添加一个商品信息
router.post('/addOrders',async function(req, res, next) {
  //将temp中的临时文件移动到images中做永久保存
  const {imagePath}=req.body
  // console.info(imagePath)
  //将图片路径进行拆分，拿到图片名称
  if(imagePath){
    const filename=imagePath.split('/').pop()
    moveFiles({
      frompath:'./public/temp',
      toPath:'./public/images',
      filename
    });
    //接收前端发送过来的数据
    //get:req.query
    const data=await addOrders({...req.body,imagePath:`./images/${filename}`})
    if(data){
      removeFiles('./public/temp')
    }
    res.send(data)
  }else{
    const user=req.body
    const data = await addOrders(user);
    res.send(data);
  }
 
});







module.exports = router;